package com.example.demo.service;

import com.example.demo.common.exception.FailedException;
import com.example.demo.common.result.FailedResult;
import com.example.demo.common.status.UserStatus;
import com.example.demo.model.User;
import com.example.demo.view.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserDetailService implements UserDetailsService {

    private final UserService userService;

    @Autowired
    public UserDetailService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException{
        User user = userService.selectUserByUserName(phone);
        if(UserStatus.DELETE.getCode().equals(user.getState())){
            throw new FailedException(FailedResult.USER_IS_DELETE);
        }else if(UserStatus.DISABLE.getCode().equals(user.getState())){
            throw new FailedException(FailedResult.USER_ACCOUNT_BAN);
        }else {
            LoginVo loginVo = new LoginVo();
            loginVo.setUser(user);
            loginVo.setUserID(user.getId());
            user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
            return loginVo;
        }
    }
}
